<template>
  <div class="wrap">
    <div class="filter" :class="tabs.length > 0 ? 'top_y' : 'top_n'">
      <div class="export">
        <el-button @click="exportReport" size="mini" type="default">导出</el-button>
      </div>
      <el-form ref="form" :model="query" :rules="rules" label-width="0">
        <el-form-item label="" prop="agent">
          <el-select class="w_150" v-model="query.agent" placeholder="代理商" :clearable='clearable'>
            <el-option
              v-for="item in agentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="" prop="city">
          <el-select class="w_120" v-model="query.city" placeholder="城市" clearable>
            <el-option
              v-for="item in cityList"
              :key="item.id"
              :label="item.city_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="" prop="flow_path" v-if="hasFlowPath">
          <el-select class="w_120" v-model="query.flow_path" placeholder="类型" clearable>
            <el-option
              v-for="item in flowPathList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="" prop="industry" v-if="hasIndustry">
          <el-select class="w_120" v-model="query.industry" placeholder="行业" clearable>
            <el-option
              v-for="item in industryList"
              :key="item.id"
              :label="item.label_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="" prop="area" v-if="hasArea">
          <el-select v-model="query.area" placeholder="商圈" clearable>
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :label="item.area_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="" prop="shop_name" v-if="hasShop">
           <el-autocomplete
              class="inline-input w_180"
							v-model="shop_name"
							:fetch-suggestions="querySearchShop"
							placeholder="店铺名称"
							:trigger-on-focus="false"
							@select="handleSelectShop"
              clearable
              @clear='clearShop'
              @input="changeShop"
						></el-autocomplete>
        </el-form-item>

        <el-form-item label="" prop="company" v-if="hasCompany">
          <el-input 
            class="w_220" 
            v-model="query.company" 
            placeholder="公司名称"
          ></el-input>
        </el-form-item>

        <div class="time-warp" v-if="type === 'month'">
          <el-form-item label="" prop="start_time"  class="w_130">
            <el-date-picker
              class="w_date"
              v-model="query.start_month"
              valueFormat="yyyy-MM-dd"
              type="month"
              :picker-options="pickerStartOptions"
              :clearable="false"
              placeholder="开始月份" />
          </el-form-item>
          <span>~</span>
          <el-form-item label="" prop="end_time" class="w_130">
            <el-date-picker
              class="w_date"
              v-model="query.end_month"
              valueFormat="yyyy-MM-dd"
              type="month"
              :picker-options="pickerEndOptions"
              :clearable="false"
              placeholder="结束月份" />
          </el-form-item>
        </div>

        <div class="time-warp" v-if="type === 'week'">
          <el-form-item label="" prop="start_time" class="w_130">
            <el-date-picker
              class="w_date"
              v-model="query.start_week"
              format="yyyy 第 WW 周"
              valueFormat="yyyy-MM-dd"
              type="week"
              :picker-options="pickerStartOptions"
              :clearable="false"
              placeholder="开始周" />
          </el-form-item>
          <span>~</span>
          <el-form-item label="" prop="end_time" class="w_130">
            <el-date-picker
              class="w_date"
              v-model="query.end_week"
              format="yyyy 第 WW 周"
              valueFormat="yyyy-MM-dd"
              :picker-options="pickerEndOptions"
              type="week"
              :clearable="false"
              placeholder="结束周" />
          </el-form-item>
        </div>

        <div class="time-warp" v-if="type === 'day'">
          <el-form-item label="" prop="start_time" class="w_130">
            <el-date-picker
              class="w_date"
              type="date"
              :picker-options="pickerStartOptions"
              :clearable="false"
              v-model="query.start_day"
              valueFormat="yyyy-MM-dd"
              placeholder="开始日期" />
          </el-form-item>
          <span>~</span>
          <el-form-item label="" prop="end_time" class="w_130">
            <el-date-picker
              class="w_date"
              type="date"
              :clearable="false"
              :picker-options="pickerEndOptions"
              v-model="query.end_day"
              valueFormat="yyyy-MM-dd"
              placeholder="结束日期" />
          </el-form-item>
        </div>
      </el-form>
      <div>
        <el-button @click="search" size="mini" type="primary">搜索</el-button>
        <el-button @click="reset" size="mini" type="default" plain>重置</el-button>
      </div>
    </div>

    <el-tabs :value="type" type="card" :before-leave="switchTab">
      <el-tab-pane v-for="item in tabs" :label="item.text" :name="item.key" :key="item.key">
        <slot :name="item.key"></slot>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
// 报表搜索头
import {searchAgentList,searchCityList} from '../../../api/agent'
import {fetchIndustryJob} from '../../../api/label'
import {fetchAreaList,fetchShopList} from '../../../api/shop'
import moment from 'moment'

export default {
  name: 'SheetHeader',
  props: {
    hasIndustry: {
      type: Boolean,
      default: false,
    },
    hasFlowPath: {
      type: Boolean,
      default: false,
    },
    hasArea: {
      type: Boolean,
      default: false,
    },
    hasShop: {
      type: Boolean,
      default: false,
    },
    hasCompany: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: 'month'
    },
    tabs: {
      type: Array,
      default: () => [],
    }
  },
  data() {
    // 默认获取当月
    const start = moment().startOf('month').format('YYYY-MM-DD')
    const end = moment().endOf('month').format('YYYY-MM-DD')
    return {
      query: {
        agent: '',
        city: '',
        industry: '',
        area: '',
        flow_path: '',
        start_month: start,
        end_month: end,
        start_week: '',
        end_week: '',
        start_day: '',
        end_day: '',
        shop_id: '',
        company: ''
      },
      rules: {},
      agentList: [],
      cityList: [],
      industryList: [],
      areaList: [],
      flowPathList: [
        {id: 1, name: '灵活'},
        {id: 2, name: '灵活管家'},
      ],
      pickerStartOptions: {
        firstDayOfWeek: 1,
        disabledDate: time => {
          const max = Math.min(moment(this.query[`end_${this.type}`]).valueOf(), Date.now())
          return time.getTime() > max
        }
      },
      pickerEndOptions: {
        firstDayOfWeek: 1,
        disabledDate: time => {
          return time.getTime() > Date.now() || time.getTime() < moment(this.query[`start_${this.type}`]).valueOf()
        }
      },
      clearable: false, 
      shop_name: '',
    }
  },
  async created() {
    await this.fetchAgentList()
    this.$emit('init', this.getCurrentQuery());
    let { role_info } = JSON.parse(sessionStorage.getItem('manageInfo'));
		if(role_info.type == 1){
			this.clearable = true
		}
  },
  watch: {
    'query.agent'(id) {
      this.query.city = ''
      this.cityList = []
      this.getCityList(id)
    },
    // 关联商圈 + 行业岗位
    'query.city'(id) {
      if (this.hasArea) {
        this.query.area = ''
        if (!id) {
          this.areaList = []
        }
        else {
          this.getArea({city_id: id, agent_id: this.query.agent})
        }
      }

      if (this.hasIndustry) {
        this.query.industry = ''
        if (!id) {
          this.industryList = []
        }
        else {
            this.getIndustryJob({city_id: id})
        }
      }
    }
  },
  methods: {
    // 对外暴露获取当前的搜索条件
    getCurrentQuery() {
      const type = this.type === 'week' ? 'isoWeek' : this.type
      return {
        agent_id: this.query.agent,
        city_id: this.query.city,
        industry: this.query.industry,
        area_id: this.query.area,
        shop_id: this.query.shop_id,
        company_name: this.query.company,
        start_time: moment(this.query[`start_${this.type}`]).startOf(type).format('YYYY-MM-DD'),
        end_time: moment(this.query[`end_${this.type}`]).endOf(type).format('YYYY-MM-DD'),
        flow_path: this.query.flow_path,
        type: this.type
      }
    },
    exportReport() {
      this.$emit('export')
    },
    search() {
      this.$emit('search', this.getCurrentQuery())
    },
    reset() {
      this.query.industry = '' 
      this.query.area = '' 
      this.query.flow_path = '' 
      this.query.shop_id = '' //清空店铺id
      this.shop_name = '' //清空店铺name
      this.company = '' //清空公司
      const {start, end} = this.getDefaultTime()
      this.query[`start_${this.type}`] = start // 重置当前开始日期
      this.query[`end_${this.type}`] = end // 重置当前结束日期
      this.$emit('reset', {type: this.type})
      this.fetchAgentList()
    },
    getDefaultTime(type=this.type) {
      switch (type) {
        case 'month':
          return {
            start: moment().startOf('month').format('YYYY-MM-DD'),
            end: moment().endOf('month').format('YYYY-MM-DD')
          }
        case 'week':
          return {
            start: moment().startOf('isoWeek').format('YYYY-MM-DD'),
            end: moment().endOf('isoWeek').format('YYYY-MM-DD')
          }
        default:
          return {
            start: moment().format('YYYY-MM-DD'),
            end: moment().format('YYYY-MM-DD')
          }
      }
    },
    switchTab(curr) {
      this.$emit('switch-type', curr)
      if (!this.query[`start_${curr}`]) {
        this.query[`start_${curr}`] = this.getDefaultTime(curr).start
      }

      if (!this.query[`end_${curr}`]) {
        this.query[`end_${curr}`] = this.getDefaultTime(curr).end
      }
    },
    // 获取代理商
    async fetchAgentList() {
      try {
        // status: 1开启 2停用
        const {list} = await searchAgentList({status: 1})

        this.agentList = list
        // 默认进入页面 设置第一个代理商
        if (list.length && list[0] && list[0].id) {
          this.query.agent = list[0].id
          await this.getCityList(list[0].id)
        }
      } catch (err) {
        console.log('-err', err)
      }
    },
    //获取城市
    async getCityList(agentId) {
			try {
				let {list} = await searchCityList({ 
					agent_id: agentId,
					order:{"id":-1}
				})
				this.cityList = list
        if (this.cityList.length && this.cityList[0] && this.cityList[0].id) {
          this.query.city = this.cityList[0].id
        }
			} catch (err) {
				console.log(err)
			}
		},
    // 获取行业岗位
    async getIndustryJob(params={}) {
      try {
        const ret = await fetchIndustryJob(params)
        if (Array.isArray(ret)) {
          this.industryList = ret || []
        }
        else {
          this.industryList = []
        }
      } catch (err) {
        console.log('-err', err)
      }
    },
    // 获取商圈 依赖城市和代理商
    async getArea(params={}) {
      try {
        const ret = await fetchAreaList(params)
        this.areaList = ret.list
      } catch (err) {
        console.log('-err', err)
      }
    },
    //获取店铺
    async querySearchShop(queryString, cb) {
			if(queryString){
				try {
					let ret = await fetchShopList({
						sign_status: 30, //已合作的店铺
						status: 1, //启用的店铺
						search_list: '', //不进行分页
						fields: 'id,shop_sn,business_sn,area_id,city_id,name',
						name: queryString
					});
					ret.list.forEach((item) => {
						item.value = item.name;
					});
					var restaurants = ret.list;
					var results = queryString
					? restaurants.filter(this.createFilterShop(queryString))
					: restaurants;
					cb(results);
				} catch (err) {
					console.log("error:", err);
				}
			}
		},
		createFilterShop(queryString) {
			return (shop_name) => {
				return (
				shop_name.value
					.toLowerCase()
					.indexOf(queryString.toLowerCase()) === 0
				);
			};
		},
		handleSelectShop(item) {
			this.query.shop_id = item.id
      this.shop_name = item.name
		},
    clearShop(){
      this.query.shop_id = ''
      this.shop_name = ''
    },
    changeShop(queryString){
      if(!queryString){
        this.query.shop_id = ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  position: relative;
  >>> .el-tabs__content {
    margin-top: 100px;
  }
}
.filter {
  display: flex;
  align-items: center;
  position: absolute;
  width: 100%;
  .export {
    margin-right: 60px;
  }
}
.top_y{
  top: 70px;
}
.top_n{
  top: 30px;
}
.el-form {
  display: inline-flex;
  align-items: center;
  position: relative;
  top: 5px;
  z-index: 9999;
  .el-form-item {
    margin-right: 5px;
  }
}
.time-warp {
  display: inline-flex;
  align-items: center;
  span {
    position: relative;
    top: -5px;
    display: inline-block;
    height: 100%;
    margin-right: 5px;
  }
}
.w_date{
  width: 130px !important;
}
</style>



// WEBPACK FOOTER //
// src/components/sheet/SheetHeader.vue